package com.smartsofa.fragment;

import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.smartsofa.R;
import com.smartsofa.adapter.NewsFragmentPagerAdapter;
import com.smartsofa.entity.ChannelItem;
import com.smartsofa.main.ChannelActivity;
import com.smartsofa.recommend.ColumnHorizontalScrollView;
import com.smartsofa.tool.BaseTools;
import com.smartsofa.util.MyUtils;

public class KnowledgeFragment extends Fragment{
	/** 璇锋眰CODE */
	public final static int CHANNELREQUEST = 1;
	/** 璋冩暣杩斿洖鐨凴ESULTCODE */
	public final static int CHANNELRESULT = 10;
	//定义网络链接地址
	private String url;
	//定义网络连接超时判定变量
	private boolean network_timeout=false;
	private JSONObject json;
	private JSONArray jsonarr;
	private Boolean flag;
	
	private FragmentActivity mActivity;
	private View mParent;
	
	private ColumnHorizontalScrollView mColumnHorizontalScrollView;
	private LinearLayout mRadioGroup_content;
	
	private ArrayList<ChannelItem> userChannelList=new ArrayList<ChannelItem>();
	LinearLayout ll_more_columns;
	RelativeLayout rl_column;
	private ImageView button_more_columns;
	private ViewPager mViewPager;
	/** */
	private int columnSelectIndex = 0;
	/** */
	public ImageView shade_left;
	/**  */
	public ImageView shade_right;
	/** */
	private int mScreenWidth = 0;
	/**  */
	private int mItemWidth = 0;
	private ArrayList<Fragment> fragments = new ArrayList<Fragment>();

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view=inflater.inflate(R.layout.fragment_knowledge, container,false);
		return view;
	}
	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mActivity = getActivity();  
	    mParent = getView();
	    initView();	
	}
	
	private void initView(){
		mScreenWidth = BaseTools.getWindowsWidth(mActivity);		
		mItemWidth = mScreenWidth / 7;
		
	    mColumnHorizontalScrollView=(ColumnHorizontalScrollView) mActivity.findViewById(R.id.mColumnHorizontalScrollView);
	    mRadioGroup_content=(LinearLayout) mActivity.findViewById(R.id.mRadioGroup_content);
	    mViewPager = (ViewPager) mActivity.findViewById(R.id.mViewPager);
	    button_more_columns = (ImageView)mActivity. findViewById(R.id.button_more_columns);
		shade_left = (ImageView) mActivity.findViewById(R.id.shade_left);
		shade_right = (ImageView) mActivity.findViewById(R.id.shade_right);
		button_more_columns.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent_channel = new  Intent(mActivity.getApplicationContext(), ChannelActivity.class);
				Bundle bundle=new Bundle();
				bundle.putSerializable("userChannelList", userChannelList);
				startActivityForResult(intent_channel, CHANNELREQUEST);
//				overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
			}
		});
		initColumnData();
	}
	
	//初始化标签内容
	private void initColumnData() {
		//初始化默认标签
//		userChannelList = ((ArrayList<ChannelItem>)ChannelManage.getManage(new SQLHelper(mActivity)).getUserChannel());
//		userChannelList = (ArrayList<ChannelItem>) ChannelManage.defaultUserChannels;
		userChannelList.add(new ChannelItem(1, "推荐", 1, 1));
		//网络加载用户感兴趣的标签
		Thread contentdata=new Thread(new loadInterestTagThread());
		contentdata.start();
	}
	
	class loadInterestTagThread implements Runnable {
		public void run() {
			try {		
				url=MyUtils.getUrl()+"knowledge_getInterestTag?userId="+MyUtils.getUSERID();
				HttpGet request = new HttpGet(url);																
				BasicHttpParams httpParams = new BasicHttpParams();
				HttpConnectionParams.setConnectionTimeout(httpParams,MyUtils.REQUEST_TIMEOUT);
			    HttpClient httpClient = new DefaultHttpClient(httpParams);
	            HttpResponse httpResponse = httpClient.execute(request);							       
		       	
		      if (httpResponse.getStatusLine().getStatusCode() == 200) {
		    	network_timeout=true;
		        String jsonString = EntityUtils.toString(httpResponse.getEntity());
		        json = new JSONObject(jsonString);
		        flag=(Boolean) json.get("success");			        				      		       
		      }
		      }catch (Exception e) {
		        	 e.printStackTrace();
		      }
			Message msg = content_handler.obtainMessage();
			if(network_timeout){
				if (flag) {				
					msg.what = 1;									
				}else{
					msg.what = 2;			
				}
			}			
			else{
				msg.what = 3;						
			}
			content_handler.sendMessage(msg);
		}
	}
	
	Handler content_handler = new Handler() {
		public void handleMessage(Message msg) {			
			switch (msg.what) {		
			case 1:	
				try {
					jsonarr=json.getJSONArray("obj");
					for(int i=0;i<jsonarr.length();i++){
						JSONObject tagobj=new JSONObject();
						tagobj=jsonarr.getJSONObject(i);
						ChannelItem channel=new ChannelItem();
						channel.setName(tagobj.getString("interestName"));
						channel.setSelected(1);
						channel.setId(i+2);
						channel.setOrderId(i+2);
						userChannelList.add(channel);
					}
			        initTabColumn();
					initFragment();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;
			case 2:
				Toast.makeText(mActivity.getApplicationContext(), "数据加载失败，请稍后重试！", Toast.LENGTH_SHORT).show();
				break;
			case 3:
				Toast.makeText(mActivity.getApplicationContext(), "网络连接超时！", Toast.LENGTH_SHORT).show();
				break;
			}
		}		
	};
	
	//初始化标签
	private void initTabColumn() {
		mRadioGroup_content.removeAllViews();
		int count =  userChannelList.size();
		mColumnHorizontalScrollView.setParam(mActivity, mScreenWidth, mRadioGroup_content, shade_left, shade_right, ll_more_columns, rl_column);
		for(int i = 0; i< count; i++){
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(mItemWidth , LayoutParams.WRAP_CONTENT);
			params.leftMargin = 5;
			params.rightMargin = 5;

			TextView columnTextView = new TextView(mActivity);
			columnTextView.setTextAppearance(mActivity, R.style.top_category_scroll_view_item_text);
			columnTextView.setBackgroundResource(R.drawable.radio_buttong_bg);
			columnTextView.setGravity(Gravity.CENTER);
			columnTextView.setPadding(5, 5, 5, 5);
			columnTextView.setId(i);
			columnTextView.setText(userChannelList.get(i).getName());
			columnTextView.setTextColor(getResources().getColorStateList(R.color.top_category_scroll_text_color_day));
			if(columnSelectIndex == i){
				columnTextView.setSelected(true);
			}
			columnTextView.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
			          for(int i = 0;i < mRadioGroup_content.getChildCount();i++){
				          View localView = mRadioGroup_content.getChildAt(i);
				          if (localView != v)
				        	  localView.setSelected(false);
				          else{
				        	  localView.setSelected(true);
				        	  mViewPager.setCurrentItem(i);
				          }
			          }
//			          Toast.makeText(mActivity.getApplicationContext(), userChannelList.get(v.getId()).getName(), Toast.LENGTH_SHORT).show();
				}
			});
			mRadioGroup_content.addView(columnTextView, i ,params);
		}
	}
	
	private void selectTab(int tab_postion) {
		columnSelectIndex = tab_postion;
		for (int i = 0; i < mRadioGroup_content.getChildCount(); i++) {
			View checkView = mRadioGroup_content.getChildAt(tab_postion);
			int k = checkView.getMeasuredWidth();
			int l = checkView.getLeft();
			int i2 = l + k / 2 - mScreenWidth / 2;
			// rg_nav_content.getParent()).smoothScrollTo(i2, 0);
			mColumnHorizontalScrollView.smoothScrollTo(i2, 0);
			// mColumnHorizontalScrollView.smoothScrollTo((position - 2) *
			// mItemWidth , 0);
		}
		//鍒ゆ柇鏄惁閫変腑
		for (int j = 0; j <  mRadioGroup_content.getChildCount(); j++) {
			View checkView = mRadioGroup_content.getChildAt(j);
			boolean ischeck;
			if (j == tab_postion) {
				ischeck = true;
			} else {
				ischeck = false;
			}
			checkView.setSelected(ischeck);
		}
	}
	
	private void initFragment() {
		fragments.clear();
		int count =  userChannelList.size();
		for(int i = 0; i< count;i++){
			Bundle data = new Bundle();
    		data.putString("text", userChannelList.get(i).getName());
    		data.putInt("id", userChannelList.get(i).getId());
			NewsFragment newfragment = new NewsFragment();
			newfragment.setArguments(data);
			fragments.add(newfragment);
		}
		NewsFragmentPagerAdapter mAdapetr = new NewsFragmentPagerAdapter(mActivity.getSupportFragmentManager(), fragments);
		mViewPager.setAdapter(mAdapetr);
		mViewPager.setOnPageChangeListener(pageListener);
	}
	
	public OnPageChangeListener pageListener= new OnPageChangeListener(){

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageSelected(int position) {
			// TODO Auto-generated method stub
			mViewPager.setCurrentItem(position);
			selectTab(position);
		}
	};

	
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		switch (requestCode) {
		case CHANNELREQUEST:
			if(resultCode == CHANNELRESULT){
				initColumnData();
			}
			break;

		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

}
